<?php
declare (strict_types=1);

namespace app\api\controller\user;

use app\api\controller\Base;
use app\common\service\lib\sms\Sms;
use app\common\service\lib\sms\SmsFactory;
use app\common\service\lib\sms\SmsTreasure;
use app\common\service\user\LoginService;
use app\common\service\user\UserBankService;
use app\validate\BankValidate;
use app\validate\PhoneRegister;
use think\exception\ValidateException;
use think\facade\Cache;
use think\Request;

class BankBind extends Base
{

    /**
     * Author:Yingbo Sun
     * 银行卡绑定
     * @return mixed
     */
    public function bindBank()
    {
        $post = $this->request->post();
        try {
            validate(BankValidate::class)->check([
                'credit_card_numbers' => $post['credit_card_numbers'],
                'identity_card' => $post['identity_card'],
                'name' => $post['name'],
            ]);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            $data = ['code' => 400, 'message' => $e->getError()];
            return $this->res($data);
        }
        $post['uid'] = $this->request->uid;
        $data = UserBankService::bindBank($post);
        return $this->res($data);
    }

    /**
     * Author:Yingbo Sun
     * 发送短信
     * @return mixed|void
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public function sendSms()
    {
        $params = $this->request->post();
        if (empty($params['phone'])) {
            $data = ['code' => 400, 'message' => '参数错误'];
            return $this->res($data);
        }
        $code = verifyCode();
        //发送验证码
        $data = Sms::sendSms($params['phone'], $code);
        if ($data['code'] == 200) {
            Cache::store('redis')->set($params['phone'] . "code", $code, 120);
            return $this->result($data, 200, '发送成功');
        }
        return $this->result($data, 400, '发送失败');
    }

    /**
     * Author:Yingbo Sun
     * 短信验证
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public function semVerification()
    {
        $params['phone'] = $this->request->post('phone', 0, 'trim');
        $params['code'] = $this->request->post('code', 0, 'trim');
        //验证参数
        $this->validateFail(PhoneRegister::class, $params);
        $code = Cache::store('redis')->get($params['phone'] . 'code');
        if ($params['code'] !== $code) {
            return $this->result([], 400, '验证码错误');
        }
        return $this->result([], 200, '验证成功');
    }
}
